<?php

namespace App\Http\Requests;

use App\Entities\ProductEntity;
use App\Entities\ProductSkuEntity;
use App\Utils\Assert;
use Illuminate\Foundation\Http\FormRequest;

class StoreCartItemRequest extends FormRequest
{
    use BaseRequestTrait;

    /**
     * @var ProductSkuEntity
     */
    private $productSku;

    public function rules()
    {
        return [
            'productSkuId' => [
                'required',
                function ($attribute, $value, $fail) {
                    $productSkuEntity = ProductSkuEntity::find($value);
                    $this->productSku = $productSkuEntity;
                    if (is_null($productSkuEntity)) {
                        return $fail('该服务不存在');
                    }

                    $productEntity = ProductEntity::find($productSkuEntity->getProductId());
                    Assert::notNull($productSkuEntity);
                    if (!$productEntity->getOnSale()) {
                        return $fail('该服务未上架');
                    }
                },
            ],
            'num' => 'bail|required',
            'assignDate' => 'bail|required',
            'assignTime' => 'bail|required',
        ];
    }

    public function messages()
    {
        return [
            'productSkuId.required' => '请选择服务项目',
            'num.required' => '请选择购买数量',
        ];
    }

    /**
     * @return ProductSkuEntity
     */
    public function getProductSku(): ProductSkuEntity
    {
        return $this->productSku;
    }
}
